package org.timeismoney.payment.web.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.timeismoney.payment.common.Constants;
import org.timeismoney.payment.common.Md5Util;
import org.timeismoney.payment.service.StudentService;
import org.timeismoney.payment.service.TeacherService;
import org.timeismoney.payment.web.form.LoginForm;

public class WelcomeAction extends BaseAction {
	private StudentService	studentService;
	private TeacherService	teacherService;

	public void setStudentService(StudentService studentService) {
		this.studentService = studentService;
	}

	public void setTeacherService(TeacherService teacherService) {
		this.teacherService = teacherService;
	}

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		LoginForm loginForm = (LoginForm) form;
		String type = loginForm.getType();
		ActionForward forward = null;
		
		Object currentUser = null;
		String md5Pwd = "";
		if(!StringUtils.isEmpty(loginForm.getPwd())){
			md5Pwd = Md5Util.MD5(loginForm.getPwd().trim());
		}
		if ("teacher".equals(type)) {
			currentUser = teacherService.validate(loginForm.getLoginid(), md5Pwd);
			forward = mapping.findForward("teacher");
		} else if ("student".equals(type)) {
			currentUser = studentService.validate(loginForm.getLoginid(), md5Pwd);
			forward = mapping.findForward("stu");
		} else {
			return mapping.findForward("failed");
		}
		
		if(currentUser!=null){
			request.getSession().setAttribute(Constants.USER_IN_SESSION, currentUser);
		}else{
			forward = mapping.findForward("failed");
			request.setAttribute(ERROR, "登录名或密码错误，请重新输入！");
			return forward;
		}
		return forward;
	}

}
